import java.util.ArrayList;
import java.util.List;

/**
 * @Author ZhangCuirong
 * @Date 2025/8/14 8:23
 * @description:
 */
public class Solution22 {
    public void backtrack(int n, int leftLen, int rightLen, StringBuilder path, List<String> res) {
        if (leftLen + rightLen == 2 * n) {
            res.add(path.toString());
            return;
        }
        if (leftLen < n) {
            path.append("(");
            backtrack(n, leftLen + 1, rightLen, path, res);
            path.deleteCharAt(path.length() - 1);
        }
        if (rightLen < leftLen) {
            path.append(")");
            backtrack(n, leftLen, rightLen + 1, path, res);
            path.deleteCharAt(path.length() - 1);
        }
    }

    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        backtrack(n, 0, 0, new StringBuilder(), res);
        return res;
    }

    public static void main(String[] args) {
        Solution22 solution = new Solution22();
        List<String> res = solution.generateParenthesis(3);
        System.out.println(res);
    }
}
